package com.ttxs.common.security.util;

import com.ttxs.common.core.utils.SpringUtils;
import com.ttxs.common.core.vo.LoginUser;
import com.ttxs.common.core.vo.Token;
import com.ttxs.common.redis.RedisService;
import com.ttxs.common.security.properties.TokenProperties;

import java.time.Duration;
import java.util.UUID;

public class TokenUtils {
    private static RedisService redisService = SpringUtils.getBean(RedisService.class);
    private static TokenProperties tokenProperties = SpringUtils.getBean(TokenProperties.class);

    static Token createToken(LoginUser loginUser) {
        long currTime = System.currentTimeMillis();
        Token token = new Token(currTime, currTime + tokenProperties.getExpire() * 60 * 1000, UUID.randomUUID().toString());
        redisService.set(getToken(token.getToken()), loginUser, Duration.ofMinutes(tokenProperties.getExpire()));
        return token;
    }

    static Token createToken(LoginUser loginUser, String rawToken) {
        long currTime = System.currentTimeMillis();
        Token token = new Token(currTime, currTime + tokenProperties.getExpire() * 60 * 1000, rawToken);
        redisService.set(getToken(token.getToken()), loginUser, Duration.ofMinutes(tokenProperties.getExpire()));
        return token;
    }

    static LoginUser getLoginUser(String token) {
        return (LoginUser) redisService.get(getToken(token));
    }

    static void logout(String token) {
        redisService.del(getToken(token));
    }

    static boolean isLogin(String rawToken) {
        return redisService.hasKey(getToken(rawToken));
    }

    private static String getToken(String rawToken) {
        return tokenProperties.getLoginKeyPrefix() + rawToken;
    }


}
